//
//  File.swift
//  CooperSwift
//
//  Created by 计海峰 on 2021/4/26.
//  Copyright © 2021 CooperSwift. All rights reserved.
//

import Foundation

public extension UserDefaults {
    subscript(key: String) -> Any? {
        get {
            return object(forKey: key)
        }
        set {
            set(newValue, forKey: key)
        }
    }
    func float(forKey key: String) -> Float? {
        return object(forKey: key) as? Float
    }
    func date(forKey key: String) -> Date? {
        return object(forKey: key) as? Date
    }
    /// - Parameters:
    /// - type: Class that conforms to the Codable protocol.
    /// - key: Identifier of the object.
    /// - decoder: Custom JSONDecoder instance. Defaults to `JSONDecoder()`.
    /// - Returns: Codable object for key (if exists).
    func object<T: Codable>(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
        guard let data = self.value(forKey: key) as? Data else { return nil }
        return try? decoder.decode(type.self, from: data)
    }
    /// - Parameters:
    /// - object: Codable object to store.
    /// - key: Identifier of the object.
    /// - encoder: Custom JSONEncoder instance. Defaults to `JSONEncoder()`.
    func set<T: Codable>(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
        let data = try? encoder.encode(object)
        self.set(data, forKey: key)
    }
}
